package com.heima.behavior.inteceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Component
@Slf4j
public class ApTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取header中的userid
        String userId = request.getHeader("userId");
        Optional<String> optional = Optional.ofNullable(userId);
        if(optional.isPresent()){

            //存入到threadLocal中
            ApUser apUser =new ApUser();
            apUser.setId(Integer.parseInt(userId));
            ApUserThreadUtil.setUser(apUser);
            log.debug("当前threadLocal存入id:{},",userId);
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ApUserThreadUtil.clear();
    }
}
